<template>
  <div class="flex-column w-full border-1">
    <toolbar style="border-bottom: 1px solid #f1f1f1" :editor="editorRef"
             :default-config="wangEditorConfig.toolbarConfig" mode="simple"/>
    <editor style="height: 500px; overflow-y: auto" v-model="contentValue"
            :default-config="wangEditorConfig.editorConfig"
            mode="simple" @onCreated="handleCreated" @onChange="handleChange"/>
  </div>
</template>

<script setup name="WangEditor">
import {onBeforeUnmount, shallowRef} from "vue";
import '@wangeditor/editor/dist/css/style.css';
import {Editor, Toolbar} from "@wangeditor/editor-for-vue";
import {Upload} from "@/common/constant.js";
import {CacheUtil} from "@/utils/cacheUtil.js";
import {ElMessage} from "element-plus";

const contentValue = ref('');
const emits = defineEmits(["onChange"]);
const props = defineProps({
  content: {
    type: String,
    required: false
  }
})
const wangEditorConfig = reactive({
  toolbarConfig: {
    toolbarKeys: [
      'headerSelect',
      'bold', // 加粗
      'underline', // 下划线
      'bulletedList', // 无序列表
      'numberedList', // 有序列表
      'color', // 文字颜色
      'fontSize', // 字体大小
      'lineHeight', // 行高
      'uploadImage', // 上传图片
      'delIndent', // 缩进
      'indent', // 增进
      'deleteImage', //删除图片
      'divider', // 分隔线
      'insertTable', // 插入表格
      'justifyCenter', // 居中对齐
      'justifyJustify', // 两端对齐
      'justifyLeft', // 左对齐
      'justifyRight', // 右对齐
      'undo', // 撤销
      'redo', // 重做
      'clearStyle', // 清除格式
      'fullScreen', // 全屏
    ],
  },
  editorConfig: {
    placeholder: '请输入内容...',
    scroll: true,
    MENU_CONF: {
      uploadImage: {
        fieldName: 'file',
        server: Upload.URL,
        headers: {
          loginToken: CacheUtil.getToken(),
          appKey: import.meta.env.VITE_APP_KEY,
        },
        meta: {
          fileType: Upload.FILETYPE.IMAGE,
          type: Upload.TYPE.SELLER,
        },
        maxFileSize: 3 * 1024 * 1024,
        maxNumberOfFiles: 6,
        allowedFileTypes: [],
        customInsert(res, insertFn) {
          if (res.code === 100) {
            insertFn(res.data.filePath, '', '');
          } else {
            ElMessage.warning('上传失败');
          }
        },
      },
    },
  }
});

//富文本
const editorRef = shallowRef();

function handleCreated(editor) {
  editorRef.value = editor;
}

function handleChange(editor) {
  emits('onChange', editor.getHtml());
}

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor) {
    editor.destroy();
  }
})
watch(() => props.content, v => {
      contentValue.value = v;
    },
    {immediate: true, deep: true}
)
</script>
<style scoped lang="scss">

:deep(.w-e-text-container .w-e-text-placeholder) {
  top: 12px !important;
}
</style>